import type { ProColumns } from "@ant-design/pro-components";
import {
  EditableProTable,
  ProCard,
  ProFormField,
  ProFormRadio,
} from "@ant-design/pro-components";
import React, { useState } from "react";

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

type DataSourceType = {
  id: React.Key;
  name?: string;
  type?: string;
  url?: string;
};

const defaultData: DataSourceType[] = [
  {
    id: 624748504,
    name: "摄像头一",
    type: "RTSP",
    url: "xxxxxxxxxx",
  },
  {
    id: 624691229,
    name: "摄像头二",
    type: "RTSP",
    url: "xxxxxxxxxx",
  },
];

export default function Camera() {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const columns: ProColumns<DataSourceType>[] = [
    {
      title: "名称",
      key: "name",
      dataIndex: "name",
      width: "15%",
    },
    {
      title: "类型",
      key: "type",
      dataIndex: "type",
      valueType: "select",
      valueEnum: {
        RTSP: { text: "RTSP", status: "RTSP" },
        FLV: {
          text: "FLV",
          status: "FLV",
        },
        WEBRTC: {
          text: "WEBRTC",
          status: "WEBRTC",
        },
      },
    },
    {
      title: "流媒体地址",
      dataIndex: "url",
      fieldProps: (form, { rowKey, rowIndex }) => {
        if (rowIndex > 9) {
          return {
            disabled: true,
          };
        }
        return {};
      },
    },
    {
      title: "操作",
      valueType: "option",
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <div>
      <EditableProTable<DataSourceType>
        rowKey="id"
        headerTitle="摄像头配置"
        maxLength={5}
        scroll={{
          x: 960,
        }}
        recordCreatorProps={{
          record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
        }}
        loading={false}
        columns={columns}
        request={async () => ({
          data: defaultData,
          total: 3,
          success: true,
        })}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          type: "multiple",
          editableKeys,
          onSave: async (rowKey, data, row) => {
            console.log(rowKey, data, row);
            await waitTime(1000);
          },
          onChange: setEditableRowKeys,
        }}
      />
    </div>
  );
}
